package com.example.sec_demo.config;

import com.example.sec_demo.entity.Users;
import com.example.sec_demo.service.IUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.SecurityFilterChain;

import javax.annotation.Resource;
import java.security.Principal;

@Configuration
public class MyConfig {
    @Resource
    IUserService iUserService;
    @Resource
    Users query;
    Principal principal;
    @Bean
    public UserDetailsService users() {
        // The builder will ensure the passwords are encoded before saving in memory
        String name = principal.getName();
        query = iUserService.query(name);


        User.UserBuilder users = User.withDefaultPasswordEncoder();
        UserDetails admin = users
                .username(query.getUsername())
                .password(query.getPassword())
                //.authorities("")
                .roles(query.getRole()) // ["ROLE_"]
                .build();
        return new InMemoryUserDetailsManager(admin);
    }

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {

        // 开始 配置自定义的信息
        http.formLogin().loginPage("/login.html")
                .usernameParameter("myname") // 设置接收的自定义的用户的参数
                .passwordParameter("mypwd")  // 设置接收自定义的用户的密码
                .loginProcessingUrl("/userlogin") // 登录的路径 跟html或者jsp中的登录路径保持一致即可
                .defaultSuccessUrl("/success").permitAll() // 默认的成功的路径
                .and().authorizeRequests().antMatchers("/", "/userlogin").permitAll()
                .and().authorizeRequests().antMatchers("/test/**").hasAuthority("ROLE_USER") // 有user的权限
                .anyRequest().authenticated() // 除去不需要认证的路径的其它路径都放行
                .and().exceptionHandling().accessDeniedPage("/403.html") // 自定义没有权限的页面
                .and()
                .csrf().disable();// 关闭csrf的保护

        DefaultSecurityFilterChain build = http.build();
        return build;

    }

}
